package com.longxi.tianjintianbao.ui.presenter.energy_read;

import android.app.AlertDialog;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.SelectMeterListener;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.model.meter.Meter;
import com.longxi.tianjintianbao.ui.adapter.multitype.LabelViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.energy_read.EnergyMeterViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.energy_read.IEnergyWriteListAtView;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class EnergyWriteListAtPresenter extends BasePresenter<IEnergyWriteListAtView> {

    private MultiTypeAdapter adapter;
    private Items items;
    List<Meter> meterList = new ArrayList<>();

    int buildid;
    String metertype = "";
    String meterscategory = "";

    public EnergyWriteListAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        buildid = intent.getIntExtra(AppConst.BUILDID, 0);
        metertype = intent.getStringExtra(AppConst.METERTYPE);
        meterscategory = intent.getStringExtra(AppConst.METERSCATEGORY);

        String title = "";
        if("1".equals(metertype)){
            title = "房间区域";
        }else{
            title = "公共区域";
        }

        if("1".equals(meterscategory)){
            title = title + "水表";
        }else{
            title = title + "电表";
        }
        mContext.setTitle(title);
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(String.class, new LabelViewBinder());
            adapter.register(Meter.class, new EnergyMeterViewBinder(listener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    /**
     * 获取抄表列表
     */
    public void getMetersList() {
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            if(buildid == 0){
                object.put("buildid", "");
            }else{
                object.put("buildid", buildid);
            }
            object.put("metertype", metertype);
            object.put("metercategory", meterscategory);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getMetersList(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Meter>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                MyUtils.showToast(throwable.message);
                mContext.showError();
            }

            @Override
            public void onNext(HttpResult<Meter> result) {
                meterList = result.getData();
                if(meterList.size() == 0){
                    mContext.showNoData();
                    return;
                }
                groupBys();
            }
        });
    }

    /**
     * 弹出抄表框
     */
    public void showEnterDialog(Meter meter){
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.popup_enter_meter, null);
        builder.setView(view);
        final AlertDialog dialog = builder.show();
        final TextView mTvInstrumentNumber = view.findViewById(R.id.tvInstrumentNumber);
        final EditText mEtThisdegrees = view.findViewById(R.id.etThisdegrees);
        final TextView mTvCancle = view.findViewById(R.id.tvCancle);
        final TextView mTvSure = view.findViewById(R.id.tvSure);

        String title = "";
        if(!"".equals(meter.getMeterno())){
            title = "表号:" + meter.getMeterno();
        }
        if(!"".equals(meter.getMetername())){
            title = "表名:" + meter.getMetername();
        }
        title = title + "\t上次抄表数:" + meter.getLastdegrees();
        mTvInstrumentNumber.setText(title);
        mTvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        mTvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String thisdegrees = mEtThisdegrees.getText().toString().trim();
                if("".equals(thisdegrees)){
                    MyUtils.showToast("请输入本次抄表度数");
                }else{
                    meter.setThisdegrees(thisdegrees);
                    saveMeterDegrees(meter, thisdegrees);
                    dialog.dismiss();
                }
            }
        });
    }

    /**
     * 水电表度数保存
     */
    public void saveMeterDegrees(Meter meter, String thisdegrees){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("meterid", meter.getMeterid());
            object.put("thisdegrees", thisdegrees);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().saveMeterDegrees(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                meter.setThisdegrees(thisdegrees);
                groupBys();
                MyUtils.showToast("水电表度数保存成功");
            }
        });
    }

    /**
     * 分组拍 不知道怎么搞了 先这样吧 科科
     */
    public void groupBys() {
        Map map = new HashMap();
        String key_str = "";
        List<Meter> value_list;

        /*** 将list分组，存入map ***/
        for (Meter meter : meterList) {
            if("".equals(meter.getThisdegrees())){
                key_str = "本月未抄";
            }else{
                key_str = "本月已抄";
            }
            value_list = new ArrayList<>();

            if (key_str != null) {
                if (map.containsKey(key_str)) {
                    value_list = (List<Meter>) map.get(key_str);
                }
                value_list.add(meter);
                map.put(key_str, value_list);
            }
        }

        Map map2 = new HashMap();
        map2.put("本月已抄", map.get("本月已抄"));
        map2.put("本月未抄", map.get("本月未抄"));

        items = new Items();
        for(Object key : map2.keySet()){
            items.add(key.toString());
            List<Personnel> personnels = (List<Personnel>) map2.get(key);
            if(personnels != null){
                items.addAll(personnels);
            }
        }
        adapter.setItems(items);
        adapter.notifyDataSetChanged();
        mContext.hideLoading();
    }

    SelectMeterListener listener = new SelectMeterListener() {
        @Override
        public void onSuccess(Meter meter) {
            showEnterDialog(meter);
        }
    };

    public void onDestroy() {
        listener = null;
    }
}
